package com.ithuameng.cosy.config;

import com.ithuameng.cosy.constants.Constants;
import com.ithuameng.cosy.service.IMessageLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Slf4j
@Configuration
public class RabbitConfig {

    @Resource
    private CachingConnectionFactory cachingConnectionFactory;

    @Resource
    private IMessageLogService messageLogService;

    /***********************************************************************
     *
     *                       RabbitMQ 交换机与队列配置
     *
     ***********************************************************************/

    @Bean("cimDirectExchange")
    public Exchange cimDirectExchange() {
        return ExchangeBuilder.directExchange(Constants.CIM_MESSAGE_DIRECT_EXCHANGE).durable(true).build();
    }

    @Bean("cimBindQueue")
    public Queue cimBindQueue() {
        return QueueBuilder.durable(Constants.BIND_MESSAGE_INNER_QUEUE).build();
    }

    @Bean("cimPushQueue")
    public Queue cimPushQueue() {
        return QueueBuilder.durable(Constants.PUSH_MESSAGE_INNER_QUEUE).build();
    }

    @Bean
    public Binding cimBindQueueExchange(@Qualifier("cimBindQueue") Queue queue,
                                        @Qualifier("cimDirectExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Constants.BIND_MESSAGE_ROUTING_KEY).noargs();
    }

    @Bean
    public Binding cimPushQueueExchange(@Qualifier("cimPushQueue") Queue queue,
                                        @Qualifier("cimDirectExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(Constants.PUSH_MESSAGE_ROUTING_KEY).noargs();
    }


    /***********************************************************************
     *
     *                        RabbitMQ 消息确认机制配置
     *
     ***********************************************************************/

    @Bean
    public RabbitTemplate createRabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            // 消息唯一ID
            if (ack) {
                messageLogService.updateStatus(data.getId(), 1);
            } else {
                log.info("[" + data.getId() + "] message sending failure from confirm callback.");
            }
        });
        rabbitTemplate.setReturnsCallback((returned) -> {
            log.info("message sending failure from returns callback.");
        });
        return rabbitTemplate;
    }
}
